import Taro from '@tarojs/taro'
import axios from 'axios'
import { pageInit } from '@/SDK/'

const urlAPI = {
  development: '',
  production: '',
}

let _token = localStorage.getItem('X-Auth0-Token') || ''
// console.log("PAGE", pageInit)
if (!_token && pageInit) {
  pageInit()
}
_token = _token || window.winToken
_token = _token || ''
const setToken = (token = '') => {
  if (_token) {
    return
  }
  _token = token
}
let defaultHeader = {
  'X-Auth0-Token': _token,
}

alert('init http=====' + _token)
const DTaroAjax = (
  url = '',
  data = {},
  method = 'GET',
  Loading = true,
  tokenStatus = true,
  isQuery
) => {
  _token = localStorage.getItem('X-Auth0-Token')
  defaultHeader = {
    ...defaultHeader,
    'content-type': 'application/json',
  }

  //  用于获取验证码
  if (!tokenStatus) {
    delete defaultHeader['X-Auth0-Token']
  } else {
    window.winToken = window.winToken || ''
    defaultHeader['X-Auth0-Token'] = _token || window.winToken
  }
  /// data['time'] = new Date().getTime()
  if (data && isQuery) {
    if (typeof data === 'object') {
      let query = ''
      // let datas = Object.keys(data)
      // datas.map((item, i) => {
      //   _url = (i > 0 ? '?' : i < datas.length - 2 ? '&' : '') + (i < datas.length - 2 ? item + ('=' + data[item]) : '')
      // })
      if (Object.keys(data).length !== 0) {
        Object.keys(data).forEach(key => {
          if (data[key] || data[key] === 0) {
            query += `${key}=${data[key]}&`
          }
        })
        query = query.slice(0, query.length - 1)
        url = url + '?' + query
      }
    }
  }
  const _data = data
  return new Promise((resolve, rejects) => {
    if (Loading) {
      Taro.showLoading({
        title: '',
        icon: 'loading',
        mask: true,
        duration: 1000,
      })
      setTimeout(() => {
        Taro.hideLoading()
      }, 10000)
    }
    Taro.request({
      url: urlAPI[process.env.NODE_ENV] + url,
      data: _data,
      method: method.toUpperCase(),
      header: defaultHeader,
    })
      .then(({ data }) => {
        Taro.hideLoading()
        if (+data.code === 0) {
          return resolve(data.data)
        } else if (+data.code === -401) {
          // token失效
          // 退出登录
          localStorage.removeItem('X-Auth0-Token')
          window.winToken = ''
          Taro.showToast({
            title: '您的账户已失效',
            icon: 'none',
            duration: 800,
          }).then(() => {
            setTimeout(() => {
              if (window.bridge) {
                window.bridge.callHandler('logout', {}, function responseCallback(res) {})
              }
            }, 1000)
          })
        }
        // else if (+data.code === 40001) { //  ||
        //Taro.navigateTo({
        //   url: '/pages/error/error'
        //})
        // return
        // }
        else {
          return Taro.showToast({
            title: data.msg,
            icon: 'none',
          })
        }
      })
      .catch(res => {
        Taro.hideLoading()
        Taro.navigateTo({
          url: '/pages/error/error',
        })
        return rejects(res)
      })
  })
}

const DTaroUpload = (url = '', filePath) => {
  //defaultHeader['content-type'] = 'multipart/form-data'
  defaultHeader = {
    ...defaultHeader,
  }
  return new Promise((resolve, rejects) => {
    Taro.uploadFile({
      url: url,
      filePath: filePath,
      name: 'file',
      header: defaultHeader,
    })
      .then(({ data }) => {
        resolve(data)
      })
      .catch(({ data }) => {
        rejects(data)
      })
  })
}

const DTaroDownload = url => {
  defaultHeader = {
    ...defaultHeader,
  }
  return new Promise((res, rej) => {
    axios({
      url,
      // params: data,
      method: 'get',
      responseType: 'blob',
      headers: defaultHeader,
    })
      .then(({ data }) => {
        const url = URL.createObjectURL(data)
        res(data, url)
      })
      .catch(({ data }) => {
        rej(data)
      })
  })
}

export { DTaroAjax, DTaroUpload, setToken, DTaroDownload }
